package pl.th.permission.plugin.node.annotation;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import pl.th.permission.plugin.Utils;

public class PartAnnotation extends AllAnnotation{

    protected Set<String> permissions;

    public PartAnnotation(AnnType type) {
        super(type);
        this.permissions = new LinkedHashSet<>(4);
    }

    public Set<String> getPermissions() {
        if (permissions == null || permissions.isEmpty()) {
            throw new RuntimeException("the permission array should not be empty for the annotation: " + mAnnType);
        }
        return permissions;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void visitEnd() {
        super.visitEnd();
        final int index = values.indexOf(Utils.PERMISSIONS_NAME);
        final List<Object> array = (List<Object>) values.get(index + 1);
        for (Object o : array) permissions.add((String) o);
    }

    @Override
    public boolean checkAnnotationType(AnnType type) {
        return type == AnnType.ON_PERMISSION_GRANTED ||
                type == AnnType.ON_PERMISSION_DENIED;
    }

    @Override
    public String getMethodDesc() {
        return Utils.METHOD_DESC_PARTIAL_OR_ALL_CALLBACK;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;
        PartAnnotation that = (PartAnnotation) o;
        return Objects.equals(permissions, that.permissions);
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), permissions);
    }

    @Override
    public String toString() {
        return "PartAnnotation{" +
                "permissions=" + permissions +
                "} " + super.toString();
    }
}
